<template>
  <div class="add-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!--       :active="activeIndex -0 "只接受数字型，所以需要转换数据类型，直接 -0 即可-->

      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        label-position="top"
        :rules="rules"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeLeave"
          @tab-click="tabClickFn"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="form.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="form.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="form.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="list"
                :props="cascaderProps"
                v-model="form.goods_cat"
                @change="changeFn"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="aa"
                  v-for="(aa, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="successFn"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="form.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top: 15px" @click="addFn"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="previewPath" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import {
  addGoodsApi,
  getCategoriesAttributesApi,
  getGoodsCategoriesApi,
} from "@/api/e-commerce";
import { Message } from "element-ui";

// require styles
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";

export default {
  components: {
    quillEditor,
  },
  name: "AddPage",
  data() {
    return {
      list: [],
      selectedKeys: "",
      activeIndex: 0,
      form: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      rules: {
        goods_name: [{ required: true, message: "请输入商品名称" }],
        goods_price: [{ required: true, message: "请输入商品价格" }],
        goods_number: [{ required: true, message: "请输入商品数量" }],
        goods_weight: [{ required: true, message: "请输入商品重量" }],
        goods_cat: [{ required: true, message: "请选择商品分类" }],
      },
      manyData: [],
      onlyData: [],
      uploadURL: "https://lianghj.top:8888/api/private/v1/upload",
      headers: {
        Authorization: this.$store.state.user.token,
      },
      previewPath: "",
      dialogVisible: false,
    };
  },
  created() {
    this.getGoodsCategories();
  },
  computed: {
    cateId() {
      if (this.form.goods_cat.length === 3) {
        return this.form.goods_cat[2];
      }
      return null;
    },
  },
  methods: {
    async addFn() {
      try {
        await this.$refs.form.validate();
        this.form.goods_cat = this.form.goods_cat.join(",");
        console.log("提交");
        this.manyData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.form.attrs.push(newInfo);
          console.log(this.form);
        });
        this.onlyData.forEach((item) => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
          this.form.attrs.push(newInfo);
        });
        const res = await addGoodsApi(this.form);
        console.log(res);
        Message.success("添加商品成功");
        this.$router.push("/goods");
      } catch (err) {
        Message.error("请填写必要的表单项");
      }
    },
    // 图片上次成功的钩子
    successFn(response) {
      console.log(response);
      const pic = { pic: response.data.tmp_path };
      this.form.pics.push(pic);
      console.log(this.form);
    },
    // 图片预览
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file) {
      console.log(file);
      const path = file.response.data.tmp_path;
      // 用filter方法会更简单
      // 返回找到的这一项的索引
      const res = this.form.pics.findIndex((a) => a.pic === path);
      this.form.pics.splice(res, 1);
      console.log(this.form);
    },
    async tabClickFn() {
      try {
        if (this.activeIndex === "1") {
          // console.log(this.activeIndex);
          const { data: res } = await getCategoriesAttributesApi(this.cateId, {
            sel: "many",
          });
          console.log(res.data);
          res.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          });
          this.manyData = res.data;
        } else if (this.activeIndex === "2") {
          // console.log(this.activeIndex);
          const { data: res } = await getCategoriesAttributesApi(this.cateId, {
            sel: "only",
          });
          console.log(res.data);
          this.onlyData = res.data;
        }
      } catch (err) {
        console.log(err);
      }
    },
    beforeLeave(activeName, oldActiveName) {
      // 这里的0得是字符串类型  因为在data里定义的就是字符串，否则不生效
      if (oldActiveName === "0" && this.form.goods_cat.length !== 3) {
        Message.error("请选择商品分类");
        return false;
      }
    },
    async getGoodsCategories() {
      const res = await getGoodsCategoriesApi();
      console.log(res);
      this.list = res.data.data;
    },
    // 当没有选中三级时，清空下拉选框
    changeFn() {
      console.log(this.form.goods_cat);
      if (this.form.goods_cat.length !== 3) {
        this.form.goods_cat = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-alert {
  margin-bottom: 15px;
}
::v-deep .el-step__title {
  font-size: 13px;
}
.el-steps {
  margin-bottom: 15px;
}
.el-checkbox {
  margin: 0 8px 10px 0;
}
::v-deep .ql-editor {
  min-height: 300px;
}
</style>
